/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.file;

import static fr.adama.constante.Constante.*;
import fr.adama.dto.AdherentDTO;
import fr.adama.dto.ContratDTO;
import fr.adama.dto.EmployeDTO;
import fr.adama.exception.ImportEntityException;
import fr.adama.service.ImportEntityFromFileService;
import fr.adama.util.DateFormatFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author avisto
 */
@Component
public class ImportEntity {

    @Value("${inputFolder}")
    String inputFolder;

    String raison = "raison.txt";
    private static final Logger logger = LoggerFactory.getLogger(ImportEntity.class);
    @Autowired
    ImportEntityFromFileService importEntityFromFileService;

    @PostConstruct
    public void createDirectoryIfNotExist() {
        logger.info("Creation des dossiers input {}", inputFolder);
        File folder = new File(inputFolder);
        File folderAtraiter = new File(inputFolder + "/" + aTraiter);
        File folderSuccess = new File(inputFolder + "/" + success);
        File folderError = new File(inputFolder + "/" + error);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        if (!folderAtraiter.exists()) {
            folderAtraiter.mkdirs();
        }
        if (!folderSuccess.exists()) {
            folderSuccess.mkdirs();
        }
        if (!folderError.exists()) {
            folderError.mkdirs();
        }
    }

    public AdherentDTO extractAdherentFromFile(HSSFWorkbook wb) {
        AdherentDTO adherent = new AdherentDTO();

        HSSFSheet sheet = wb.getSheetAt(0);
        int columnA = CellReference.convertColStringToIndex("A");
        HSSFRow row = sheet.getRow(4);
        HSSFCell cell = row.getCell(columnA);

        adherent.setNomPrenom(cell.getStringCellValue());
        row = sheet.getRow(5);
        cell = row.getCell(columnA);
        adherent.setAdresse(cell.getStringCellValue());
        row = sheet.getRow(6);
        cell = row.getCell(columnA);
        adherent.setComplementAdresse(cell.getStringCellValue());
        row = sheet.getRow(7);
        cell = row.getCell(columnA);
        adherent.setCodePostal(cell.getStringCellValue().split(" ")[0].replace(" ", ""));
        adherent.setVille(cell.getStringCellValue().split(" ")[1]);

        row = sheet.getRow(8);
        cell = row.getCell(columnA);
        String telephone = cell.getStringCellValue().split("TEL")[1].replace(":", "").replace(" ", "").trim();

        if (telephone.split("/").length == 2) {
            adherent.setTelephone(telephone.split("/")[0]);
            adherent.setMobile(telephone.split("/")[1]);
        } else {
            adherent.setTelephone(telephone);
        }
        row = sheet.getRow(9);
        cell = row.getCell(columnA);
        String mobile = cell.getStringCellValue();
        if (!mobile.isEmpty()) {
            mobile = cell.getStringCellValue().split("TEL")[1].replace(":", "").replace(" ", "").trim();
            adherent.setMobile(mobile);

        }

        row = sheet.getRow(12);
        cell = row.getCell(columnA);
        adherent.setNumUrssaf(cell.getStringCellValue());
        row = sheet.getRow(13);
        cell = row.getCell(columnA);
        adherent.setNumSiret(cell.getStringCellValue().split(":")[1].replace(":", "").trim());

        return adherent;

    }

    public EmployeDTO extractEmployeFromFile(HSSFWorkbook wb) {
        EmployeDTO employe = new EmployeDTO();

        HSSFSheet sheet = wb.getSheetAt(0);
        int columnB = CellReference.convertColStringToIndex("B");
        int columnC = CellReference.convertColStringToIndex("C");
        int columnD = CellReference.convertColStringToIndex("D");
        int columnE = CellReference.convertColStringToIndex("E");
        int columnF = CellReference.convertColStringToIndex("F");

        HSSFRow row = sheet.getRow(3);
        HSSFCell cell = row.getCell(columnD);
        employe.setNom(cell.getStringCellValue());

        cell = row.getCell(columnF);
        employe.setPrenom(cell.getStringCellValue());

        row = sheet.getRow(4);
        cell = row.getCell(columnD);
        employe.setNomJeuneFille(cell.getStringCellValue());

        row = sheet.getRow(5);
        cell = row.getCell(columnD);
        employe.setAdresse(cell.getStringCellValue());

        row = sheet.getRow(6);
        cell = row.getCell(columnD);
        employe.setComplementAdresse(cell.getStringCellValue());

        row = sheet.getRow(7);
        cell = row.getCell(columnD);
        employe.setCodePostal(cell.getStringCellValue());

        row = sheet.getRow(7);
        cell = row.getCell(columnE);
        employe.setVille(cell.getStringCellValue());

        row = sheet.getRow(8);
        cell = row.getCell(columnC);
        String telephone = cell.getStringCellValue().replace(" ", "").trim();

        if (telephone.split("/").length == 2) {
            employe.setTelephone(telephone.split("/")[0]);
            employe.setMobile(telephone.split("/")[1]);
        } else {
            employe.setTelephone(telephone);
        }

        row = sheet.getRow(9);
        cell = row.getCell(columnE);
        employe.setNumSecu(cell.getStringCellValue().replace(".", "").replace(" ", ""));

        return employe;

    }

    public ContratDTO createContrat(AdherentDTO adherent, EmployeDTO employe, HSSFWorkbook wb) throws ParseException {
        ContratDTO contrat = new ContratDTO();
        HSSFSheet sheet = wb.getSheetAt(0);
        int columnE = CellReference.convertColStringToIndex("E");
        int columnC = CellReference.convertColStringToIndex("C");
        HSSFRow row = sheet.getRow(10);
        HSSFCell cell = row.getCell(columnE);
        contrat.setDateEntree(DateFormatFactory.getDateFormatContrat().parse(cell.getStringCellValue()));
        row = sheet.getRow(16);
        cell = row.getCell(columnC);
        contrat.setSalaireBase(new BigDecimal(cell.getNumericCellValue()));
        return contrat;

    }

    public void importFile() throws IOException {
        File folder = new File(inputFolder + "/" + aTraiter);
        File[] listFile = folder.listFiles();
        ArrayList<File> moveToError = new ArrayList<>();
        ArrayList<File> moveToSuccess = new ArrayList<>();

        logger.info("Il y a " + listFile.length + " document à importer");

        for (int i = 0; i < folder.listFiles().length; i++) {
            File file = null;
            try {
                file = folder.listFiles()[i];
                HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
                logger.info("Extraction de l'adherent du fichier {}", file.getName());
                AdherentDTO adherent = extractAdherentFromFile(wb);
                logger.info("Extraction de l'employe du fichier {}", file.getName());
                EmployeDTO employe = extractEmployeFromFile(wb);
                logger.info("Extraction du contrat du fichier {}", file.getName());
                ContratDTO contrat = createContrat(adherent, employe, wb);
                importEntityFromFileService.addEntity(adherent, employe, contrat, file.getName());
                moveToSuccess.add(file);
            } catch (FileNotFoundException ex) {
                logger.error("Fichier inexistant", ex);
                FileUtils.writeStringToFile(new File(inputFolder + "/" + error + "/" + file.getName() + ".txt"), ex.getMessage());

                moveToError.add(file);
            } catch (IOException ex) {
                logger.error("Problème de lecture du fichier", ex);
                FileUtils.writeStringToFile(new File(inputFolder + "/" + error + "/" + file.getName() + ".txt"), ex.getMessage());

                moveToError.add(file);
            } catch (ImportEntityException | ParseException ex) {
                logger.error("Problème lors de l'import du fichier", ex);
                FileUtils.writeStringToFile(new File(inputFolder + "/" + error + "/" + file.getName() + ".txt"), ex.getMessage());
                moveToError.add(file);
            }
        }

        for (File fileError : moveToError) {
            FileUtils.moveFile(fileError, new File(inputFolder + "/" + error + "/" + fileError.getName()));
        }
        for (File fileSuccess : moveToSuccess) {
            FileUtils.moveFile(fileSuccess, new File(inputFolder + "/" + success + "/" + fileSuccess.getName()));
        }
    }

}
